package com.leyou.item.web;


import com.leyou.common.exceptions.LyException;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("category")
public class CategoryController {


    private final CategoryService categoryService;

    @Autowired
    public CategoryController(CategoryService categoryService){
        this.categoryService =categoryService;
    }

    /**
     *根据分类id，查询商品分类
     * @param id  商品分类id
     * @return 商品分类dto
     */
    @GetMapping("/{id}")
    public ResponseEntity<CategoryDTO> queryCategoryById(@PathVariable("id") Long id){
        return ResponseEntity.ok(new CategoryDTO(categoryService.getById(id)));
    }

    /**
     * 根据分类id的集合，查询商品分类的集合
     * @param ids 分类id集合
     * @return  商品分类集合
     */
    @GetMapping("/list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryList(@RequestParam("ids") List<Long> ids){
        //查询数据
        List<Category> categories = categoryService.listByIds(ids);

        if (CollectionUtils.isEmpty(categories)){
            throw new LyException(404 , "品牌没有关联的分类");
        }
/*        //方式一：for循环遍历
        List<CategoryDTO> dotlist = new ArrayList<>(categories.size());
        for (Category category : categories){
            dotlist.add(new CategoryDTO(category));
        }
        // 方式二：使用stream流
        List<CategoryDTO> collect1 = categories.stream().map(category -> new CategoryDTO(category)).collect(Collectors.toList());
        //方式二：简化
        List<CategoryDTO> collect = categories.stream().map(CategoryDTO::new).collect(Collectors.toList());*/

        //方式三：使用工具类
        List<CategoryDTO> dtoList = CategoryDTO.convertEntityList(categories);

        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据父类目id查询
     * @param pid  父类目
     * @return  子类目所有信息
     */
    @GetMapping("of/parent")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByPid(@RequestParam("pid") Long pid){
        //SELECT * FROM tb_category WHERE parent_id = 0
        List<Category> pidList = categoryService.query().eq("parent_id", pid).list();
        List<CategoryDTO> dtoList = CategoryDTO.convertEntityList(pidList);
        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据品牌id查询分类id
     * @param brandId 品牌id
     * @return 分类集合
     */
    @GetMapping("/of/brand")
    public ResponseEntity<List<CategoryDTO>> queryCategoryBrandById(@RequestParam("id") Long brandId){
        List<CategoryDTO> dtoList =categoryService.queryByBrand(brandId);
        return ResponseEntity.ok(dtoList);
    }


}
